import Notify from '@vant/weapp/notify/notify';
import Toast from '@vant/weapp/toast/toast';
import Dialog from '@vant/weapp/dialog/dialog';
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    mainColor: app.globalData.mainColor,
    baseImgUrl: app.globalData.baseImgUrl,
    content: "",
    fileList: [],
    localName: "",
    localAddress: "",
    lng: "",
    lat: "",
    tempLng: "",
    tempLat: "",
    userInfo: '',
    overlay: false,
  },

  afterRead(event) {
    console.log('event:', event);
    const that = this;
    const {
      file
    } = event.detail;
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    let uri = app.globalData.baseUrl + '/gd-fishing/upload/img';
    // console.log('uri:', uri);
    // console.log('file:', file);
    that.setData({
      overlay: true
    });
    wx.uploadFile({
      url: uri,
      filePath: file.url,
      header: {
        'Authorization': wx.getStorageSync('token')
      },
      name: 'file',
      formData: {},
      success(res) {
        that.setData({
          overlay: false
        });
        // console.log('success-res:',res.data);
        let jsonData = JSON.parse(res.data);
        // console.log('http-res:', jsonData.data);
        if (jsonData.code == 1) {
          const {
            fileList = []
          } = that.data;
          fileList.push({
            ...file,
            url: that.data.baseImgUrl + jsonData.data,
            address: jsonData.data
          });
          that.setData({
            fileList
          });
        }
      },
      fail(res) {
        console.log('fail-res:', res);
      },
    });
  },

  //删除图片
  delImg(e) {
    const {
      fileList = []
    } = this.data;
    fileList.splice(e.detail.index, 1);
    this.setData({
      fileList
    });
  },

  //添加地标
  addAddress() {
    let that = this;
    wx.chooseLocation({
      latitude: that.data.tempLat,
      longitude: that.data.tempLng,
      success(res) {
        // console.log('success-res:', res)
        that.setData({
          localName: res.name,
          localAddress: res.address,
          lat: res.latitude,
          lng: res.longitude,
          tempLat: res.latitude,
          tempLng: res.longitude
        });
      },
      fail(res) {
        // console.log('fail-res:', res)
      }
    })
  },
  //授权地图
  authMap() {
    // console.log('--------->begin..auth..map')
    const that = this;
    wx.getFuzzyLocation({
      type: 'wgs84',
      success(res) {
        // console.log('success-res:', res)
        // console.log('latitude:', res.latitude)
        // console.log('longitude:', res.longitude)
        that.setData({
          tempLat: res.latitude,
          tempLng: res.longitude
        });
      },
      fail(res) {
        console.log('fail-res:', res)
      }
    })
  },

  //提交数据
  subData() {
    let that = this;
    if (that.data.content == null || that.data.content == undefined || that.data.content.trim() == '') {
      Toast({
        position: 'top',
        message: '请输入分享内容~',
      });
      return;
    }
    let imgList = [];
    for (let i = 0; i < that.data.fileList.length; i++) {
      imgList.push(that.data.fileList[i].address);
    }
    let data = {
      "content": that.data.content,
      "localName": that.data.localName,
      "localAddress": that.data.localAddress,
      "lat": that.data.lat,
      "lng": that.data.lng,
      "imgList": imgList
    };
    app.http.post('/gd-fishing/info/add', data).then((res) => {
      // console.log('http-res:', JSON.stringify(res));
      if (app.errorAlert(res)) {
        return;
      }
      that.setData({
        content: '',
        localName: '',
        localAddress: '',
        lat: '',
        lng: '',
        fileList: []
      });
      Dialog.alert({
        message: '提交成功！',
      }).then(() => {
        // wx.navigateBack({
        //     delta: 1
        // })
      });
    })
  },

  //获取系統用户数据
  getUserData: function () {
    let that = this;
    //拿到token获取用户信息
    // app.http.get('/gd-fishing/user/info').then((res) => {
    //   // console.log('http-res:', JSON.stringify(res));
    //   let data = "";
    //   if (res.code == 1) {
    //     data = res.data;
    //   }
    //   wx.setStorageSync('userInfo', data);
    //   that.setData({
    //     userInfo: data,
    //   })
    //   // console.log('userInfo:', wx.getStorageSync('userInfo'));
    // })
    let res = {
      "code": 1,
      "msg": "成功",
      "data": {
        "userId": 8,
        "userPhone": null,
        "nickName": "优雅的空军佬",
        "headImg": "/20241029/1730191347233.jpeg",
        "signDesc": "路虽远，行则将至！",
        "userSex": null
      },
      "remarks": null
    };
    let data = "";
    if (res.code == 1) {
      data = res.data;
    }
    wx.setStorageSync('userInfo', data);
    that.setData({
      userInfo: data,
    })
    // console.log('userInfo:', wx.getStorageSync('userInfo'));
  },

  //刷新数据
  refreshData: function () {
    let userInfo = wx.getStorageSync('userInfo');
    let logout = userInfo == null || userInfo == undefined || userInfo == '';
    this.setData({
      userInfo: logout ? '' : userInfo,
    });
    this.tips();
  },

  //跳转登录
  toLogin() {
    wx.switchTab({
      url: '/pages/mine/index'
    })
  },

  //提示
  tips() {
    if (this.data.userInfo == '') {
      return;
    }
    Notify({
      message: "服务器配置较低，图片加载缓慢，请稍作等待",
      duration: 5000,
      background: this.data.mainColor,
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.authMap();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.refreshData();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    this.getUserData();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})